<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>新闻发布系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }

        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 20px;
            max-width: 100%;
            width: 100%;
            margin: 0 auto;
            position: relative;
        }

        .user-info {
            position: absolute;
            top: 15px;
            right: 15px;
            background: rgba(255, 255, 255, 0.9);
            padding: 8px 12px;
            border-radius: 15px;
            font-size: 12px;
            color: #333;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }

        .header {
            text-align: center;
            margin-bottom: 25px;
            margin-top: 40px;
        }

        .header h1 {
            color: #333;
            font-size: 1.5em;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header p {
            color: #666;
            font-size: 0.9em;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 6px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }

        input, select, textarea {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e1e8ed;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: #fafbfc;
            box-sizing: border-box;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
            font-family: inherit;
        }

        .submit-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .submit-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .submit-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            display: none;
            width: 14px;
            height: 14px;
            border: 2px solid transparent;
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .alert {
            padding: 10px 12px;
            border-radius: 6px;
            margin-bottom: 15px;
            display: none;
            font-size: 13px;
        }

        .alert.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
            body {
                padding: 5px;
            }
            
            .container {
                padding: 15px;
                border-radius: 10px;
            }
            
            .header h1 {
                font-size: 1.3em;
            }
            
            .user-info {
                position: static;
                margin-bottom: 15px;
                text-align: center;
                border-radius: 8px;
            }
            
            .header {
                margin-top: 10px;
            }
            
            input, select, textarea {
                padding: 8px 10px;
                font-size: 16px; /* 防止iOS缩放 */
            }
            
            .submit-btn {
                padding: 10px;
                font-size: 16px;
            }
        }

        @media (min-width: 768px) {
            .container {
                max-width: 600px;
                padding: 30px;
            }
        }
    </style>
</head>
<body>
    <div class="user-info" id="userInfo" style="display: none;">
        欢迎，<span id="userName"></span>
        <button onclick="logout()" style="margin-left: 8px; padding: 4px 8px; background: #ff4757; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 11px;">退出</button>
    </div>

    <div class="container">
        <div class="header">
            <h1>📰 新闻发布系统</h1>
            <p>发布您的精彩内容</p>
        </div>

        <div id="alertContainer"></div>

        <form id="newsForm">
            <div class="form-group">
                <label for="title">✏️ 新闻标题</label>
                <input type="text" id="title" placeholder="请输入新闻标题..." required>
            </div>

            <div class="form-group">
                <label for="content">📝 新闻内容</label>
                <textarea id="content" placeholder="请输入新闻内容..." required rows="6"></textarea>
            </div>

            <div class="form-group">
                <label for="publish_date">📅 发布时间</label>
                <input type="datetime-local" id="publish_date" required>
            </div>

            <div class="form-group">
                <label for="category">🏷️ 新闻分类</label>
                <select id="category" required>
                    <option value="">请选择分类...</option>
                </select>
            </div>

            <div class="form-group">
                <label for="image">🖼️ 新闻图片（可选）</label>
                <input type="file" id="image" accept="image/*">
            </div>

            <button type="button" class="submit-btn" onclick="uploadNews()">
                <div class="loading" id="loadingSpinner"></div>
                <span id="submitText">🚀 发布新闻</span>
            </button>
        </form>
    </div>

    <script>
        const token = localStorage.getItem('token');
        const baseURL = 'http://172.20.10.2:8000/api/v1';

        // 检查登录状态并显示用户信息
        function checkAuthAndShowUser() {
            if (!token) {
                alert('请先登录');
                window.location.href = 'login.html';
                return false;
            }

            // 从localStorage获取用户信息
            const userInfoStr = localStorage.getItem('userInfo');
            if (userInfoStr) {
                try {
                    const userInfo = JSON.parse(userInfoStr);
                    document.getElementById('userName').textContent = userInfo.full_name || userInfo.email;
                    document.getElementById('userInfo').style.display = 'block';
                } catch (error) {
                    console.error('解析用户信息失败:', error);
                }
            }

            return true;
        }

        // 加载分类
        async function loadCategories() {
            try {
                const response = await fetch(`${baseURL}/categories`);
                if (!response.ok) throw new Error('获取分类失败');

                const categories = await response.json();
                const select = document.getElementById('category');
                select.innerHTML = '<option value="">请选择分类...</option>';
                
                categories.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.id;
                    option.textContent = category.name;
                    select.appendChild(option);
                });
            } catch (error) {
                alert('加载分类失败: ' + error.message);
            }
        }

        // 设置默认时间
        function setDefaultDateTime() {
            const now = new Date();
            const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
                .toISOString().slice(0, 16);
            document.getElementById('publish_date').value = localDateTime;
        }

        // 上传新闻
        async function uploadNews() {
            const title = document.getElementById('title').value.trim();
            const content = document.getElementById('content').value.trim();
            const categoryId = document.getElementById('category').value;
            const publish_date = document.getElementById('publish_date').value;

            if (!title || !content || !categoryId || !publish_date) {
                alert('请填写所有必填字段');
                return;
            }

            setLoading(true);

            try {
                // 上传新闻
                const response = await fetch(`${baseURL}/news?category_id=${categoryId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        title: title,
                        content: content,
                        publish_date: publish_date
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    if (response.status === 401 || response.status === 403) {
                        alert('登录已过期，请重新登录');
                        localStorage.removeItem('token');
                        localStorage.removeItem('userInfo');
                        window.location.href = 'login.html';
                        return;
                    }
                    throw new Error(errorData.detail || '新闻发布失败');
                }

                const newsData = await response.json();
                console.log('新闻发布成功:', newsData);

                // 上传图片（如果有）
                const imageFile = document.getElementById('image').files[0];
                if (imageFile) {
                    await uploadImage(newsData.id, imageFile);
                    alert('新闻和图片发布成功！🎉');
                } else {
                    alert('新闻发布成功！🎉');
                }

                resetForm();
            } catch (error) {
                console.error('发布失败:', error);
                alert('发布失败: ' + error.message);
            } finally {
                setLoading(false);
            }
        }

        // 上传图片
        async function uploadImage(newsId, imageFile) {
            const formData = new FormData();
            formData.append('image', imageFile);

            const response = await fetch(`${baseURL}/news/${newsId}/upload-image`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` },
                body: formData
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.detail || '图片上传失败');
            }

            return await response.json();
        }

        function setLoading(isLoading) {
            const submitBtn = document.querySelector('.submit-btn');
            const loadingSpinner = document.getElementById('loadingSpinner');
            const submitText = document.getElementById('submitText');
            
            submitBtn.disabled = isLoading;
            loadingSpinner.style.display = isLoading ? 'inline-block' : 'none';
            submitText.textContent = isLoading ? '发布中...' : '🚀 发布新闻';
        }

        function resetForm() {
            document.getElementById('newsForm').reset();
            setDefaultDateTime();
        }

        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = 'login.html';
        }

        // 页面初始化
        document.addEventListener('DOMContentLoaded', async () => {
            if (checkAuthAndShowUser()) {
                await loadCategories();
                setDefaultDateTime();
            }
        });
    </script>
</body>
</html>